<template>
  <el-cascader
    v-model="selectedRegions"
    :options="regionOptions"
    :props="cascaderProps"
    :placeholder="placeholder"
    clearable
    @change="handleChange"
  />
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { getRegionTree } from '@/api/insure'

const props = defineProps({
  modelValue: {
    type: Object,
    default: () => ({
      countryId: null,
      provinceId: null,
      cityId: null,
      districtId: null,
      townId: null
    })
  },
  placeholder: {
    type: String,
    default: '请选择地区'
  }
})

const emit = defineEmits(['update:modelValue'])

// 地区数据
const regionOptions = ref([])
// 选中的地区ID数组
const selectedRegions = ref([])

// 级联选择器配置
const cascaderProps = {
  value: 'regionId',
  label: 'regionName',
  children: 'children',
  checkStrictly: false,
  emitPath: true
}

// 获取地区树
const fetchRegionTree = async () => {
  try {
    const res = await getRegionTree()
    if (res.data && res.data.data) {
      regionOptions.value = res.data.data
      // 初始化选中的值
      initSelectedRegions()
    }
  } catch (error) {
    console.error('获取地区树失败', error)
  }
}

// 初始化选中的地区
const initSelectedRegions = () => {
  const { countryId, provinceId, cityId, districtId, townId } = props.modelValue
  const selectedIds = []

  if (countryId) selectedIds.push(countryId)
  if (provinceId) selectedIds.push(provinceId)
  if (cityId) selectedIds.push(cityId)
  if (districtId) selectedIds.push(districtId)
  if (townId) selectedIds.push(townId)

  if (selectedIds.length > 0) {
    selectedRegions.value = selectedIds
  }
}

// 处理选择变化
const handleChange = (value) => {
  if (!value || value.length === 0) {
    emit('update:modelValue', {
      countryId: null,
      provinceId: null,
      cityId: null,
      districtId: null,
      townId: null
    })
    return
  }

  // 根据选择的层级设置对应的ID
  const result = {
    countryId: null,
    provinceId: null,
    cityId: null,
    districtId: null,
    townId: null
  }

  // 根据选择的层级数量分配ID
  for (let i = 0; i < value.length; i++) {
    if (i === 0) result.countryId = value[i]
    if (i === 1) result.provinceId = value[i]
    if (i === 2) result.cityId = value[i]
    if (i === 3) result.districtId = value[i]
    if (i === 4) result.townId = value[i]
  }

  emit('update:modelValue', result)
}

// 监听外部值变化
watch(
  () => props.modelValue,
  (newVal) => {
    if (newVal && Object.values(newVal).some((val) => val !== null)) {
      initSelectedRegions()
    } else {
      selectedRegions.value = []
    }
  },
  { deep: true }
)

onMounted(() => {
  fetchRegionTree()
})
</script>
